package org.example.controller;

import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.*;
import com.aliyun.oss.model.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.example.config.AliyunOSSConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.net.URL;
import java.util.Date;

@RestController
@RequestMapping("admin/file")
@Api(tags = "文件上传接口")
public class FileUploadController {

    @Autowired
    private AliyunOSSConfig aliyunOSSConfig;

    @ApiOperation("文件上传接口")
    @PostMapping("upload/element")
    public String uploadFile(MultipartFile  file) {

        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = aliyunOSSConfig.getEndpoint();

        // 填写Bucket名称，例如examplebucket。
        String bucketName = aliyunOSSConfig.getBucketName();

        //获取原文件的文件名称后缀名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        String newFolderName = DateUtil.format(new Date(), "yyyy-MM-dd");
        String newFileName =DateUtil.format(new Date(), "HHmmssSSS");
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = newFolderName + "/" + newFileName + suffix;

        String accessKeyId = aliyunOSSConfig.getAccessKeyId();

        String accessKeySecret = aliyunOSSConfig.getAccessKeySecret();

        OSSClientBuilder builder = new OSSClientBuilder();

        OSS ossClient = builder.build(endpoint, accessKeyId, accessKeySecret);

        URL url = null;

        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file.getInputStream());

            // 上传
            ossClient.putObject(putObjectRequest);
            //创建上传文件访问的URL地址
            url = ossClient.generatePresignedUrl(bucketName, objectName, DateUtil.offsetDay(new Date(),365*10));
        }catch (Exception ce) {
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        return url.toString();
    }
}
